package com.itheima.servlet;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domin.user;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;

public class ObjectMapperText {
    private ObjectMapper mapper = new ObjectMapper();

    @Test
    public void text01() throws Exception {
        //User对象转json
        //创建user对象
        user user = new user("张三", 20);
        //转换成json字符串
        String json = mapper.writeValueAsString(user);
        System.out.println("字符串+" + json);

        //json转user对象
        user user1 = mapper.readValue(json, user.class);
        System.out.println("对象+" + user1);
    }

    @Test
    public void text02() throws Exception {
        //map集合转json   <String>类型
        //创建map集合
        HashMap<String, String> map = new HashMap<>();
        map.put("姓名", "张三");
        map.put("年龄", "20");
        String s = mapper.writeValueAsString(map);
        System.out.println("字符串+" + s);

        //jsop转map   <String>类型
        HashMap<String, String> map2 = mapper.readValue(s, HashMap.class);
        System.out.println("对象+" + map2);
    }

    @Test
    public void text03() throws Exception {
        //map集合转json   <String><user>类型
        //创建map集合
        HashMap<String, user> map3 = new HashMap<>();
        map3.put("一班", new user("张三", 22));
        map3.put("二班", new user("李四", 23));
        String s1 = mapper.writeValueAsString(map3);
        System.out.println("字符串:+" + s1);

        //json转map   <String><user>类型
        HashMap<String, user> map4 = mapper.readValue(s1, new TypeReference<HashMap<String, user>>() {
        });
        System.out.println("对象+" + map4);
    }

    @Test
    public void text04() throws Exception {
        //list转json  <String>类型
        ArrayList<String> list = new ArrayList<>();
        list.add("张三");
        list.add("李四");
        String s = mapper.writeValueAsString(list);
        System.out.println("字符串+" + s);

        //json转list   <String>
        ArrayList<String> list2 = mapper.readValue(s, ArrayList.class);
        System.out.println("对象+" + list2);
    }

    @Test
    public void text05() throws Exception {
        //list转json  <user>类型
        ArrayList<user> list = new ArrayList<>();
        list.add(new user("张三",11));
        list.add(new user("李四",22));
        String s = mapper.writeValueAsString(list);
        System.out.println("字符串+"+s);

        //json转list  <user>类型

        ArrayList<user> list2 = mapper.readValue(s, new TypeReference<ArrayList<user>>() {});
        System.out.println("对象+"+list2);
    }
}